package java8;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Stream;

public class ReduceTest1 {
    public static void main(String[] args) {
        List<String> tmp = new ArrayList<>();
        List<String> reduce = Arrays.asList("1", "2", "3", "4", "5", "6", "7", "8").parallelStream().reduce(tmp, (strings, s) -> {
            ArrayList<String> al = new ArrayList<>(); // 并行的时候这里需要new,如果用tmp的虎牙tmp会被并发操作
            al.add(s);
            return al;
        }, (l, r) -> {
            l.addAll(r); // 这里会做7次,因为合并8个结果
            return l;
        });
        System.out.println(reduce); // [1, 2, 3, 4, 5, 6, 7, 8]

        List<String> reduce2 = Arrays.asList("1", "2", "3", "4").stream().reduce((List<String>)new ArrayList<String>(), (strings, s) -> {
            strings.add(s); // 不是并行的时候这里可以直接add,因为就1个线程
            return strings;
        }, (l, r) -> {
            //List<String> list = new ArrayList<>(l);
            l.addAll(r);
            return l;
        });
        System.out.println(reduce2); // [1, 2, 3, 4]

        String ss = Stream.of("1", "2", "3", "4").reduce("haha", (acc, s) -> {
            return acc + s;
        });
        System.out.println(ss); // haha1234

    }
}
